# -*- coding: utf-8 -*-
from . import BaseController
from backend.models import User
from backend.libs.args_util import *
from backend.libs import myjson as json

class UserListController(BaseController):

    def get(self):
        args = PageArgs(self, 'get', 'nickname')
        user_state = self.int_argument('user_state', -1)
        user_from = self.int_argument('user_from', -1)

        users = User.objects
        if args.nickname:
            users = users.filter(nickName__contains=args.nickname)
        if user_state > -1:
            users = users.filter(user_state=user_state)
        if user_from > -1:
            users = users.filter(user_from=user_from)
        users = users.order_by('create_time')
        paginator = self.pagination(users.all(), number_per_page=args.pageSize)
        return self.render_json(data=paginator)


class OwnerOptionsController(BaseController):

    def get(self):
        users = User.objects.filter(user_from=2).order_by('user_state').all()
        data = [ {'label': u.nickname, 'value': u.id } for u in users ]
        return self.render_json(data={'users': data})


class ManagerOptionsController(BaseController):

    def get(self):
        users = User.objects.filter(user_from=1).filter(user_state=1).order_by('-create_time').all()
        data = [ {'label': u.nickname, 'value': u.id } for u in users ]
        return self.render_json(data={'managers': data})


class UpdateUserStateController(BaseController):

    def post(self):
        data = json.loads(self.request.body)
        id = data.get('id', '')
        user_state = int(data.get('user_state', -1))
        if not id or user_state < 0:
            return self.render_json(code=1001, msg='参数错误')
        user = User.objects.filter(id=id).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')
        if user.user_state != user_state:
            user.user_state = user_state
            user.enter_state = 2
            user.save()

        return self.render_json(data=user.to_dict(), msg='状态修改成功')

